<?php

namespace App\Admin\Http\Controllers\Web;

use App\Admin\Eloquent\Article;
use App\Admin\Eloquent\ArticleCategory;
use App\Admin\Eloquent\Code;
use App\Admin\Http\Controllers\Controller;
use App\Admin\Http\Requests\ArticleRequest;
use App\Exceptions\BusinessException;
use App\Http\Controllers\ArticleController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laracasts\Flash\Flash;

class ArticlesController extends Controller
{

    /**
     * 文章ID
     */
    const ARTICLE_TYPE_ARTICLE = 4;
    /**
     * 平台公告ID
     */
    const ARTICLE_TYPE_NOTICE = 1;
    /**
     * 帮助中心ID
     */
    const ARTICLE_TYPE_HELP = 2;
    /**
     * 关于我们ID
     */
    const ARTICLE_TYPE_ABOUT = 3;

    /**
     * 模糊查询文章列表
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $query = $request->only('title', 'article_category_id');

        $article_categories = Article::get_article_categories();
        $articles = Article::paging_query($query);

            $articles->appends($query);
            // $request->session()->put('query',$query);

        $links = $articles->render();

        return view('admin.web.articles.index', compact('query', 'article_categories', 'articles', 'links'));
    }

    /**
     * 返回创建文章表单页面
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function create(Request $request)
    {
        $request->session()->put('articleBack',back()->getTargetUrl());

        $author = $this->currentUser()->username;

        $article_categories = Article::get_article_categories();

        $article_tags = Article::get_tags();

        return view('admin.web.articles.create', compact('author', 'article_categories', 'article_tags'));
    }

    /**
     * 保存文章记录
     *
     * @param ArticleRequest $request
     * @return \Illuminate\Http\RedirectResponse
     * @throws BusinessException
     */
    public function store(ArticleRequest $request)
    {
        $args = $request->all();

        if (isset($args['tags'])) {
            $args['tags'] = implode(',', $args['tags']);
        }

        $article = new Article($args);

        if ($image = $request->file('image')) {
            $json = upload_file($image);    //上传文件
            if ($json['code'] == 10000) {
                $article->image = "{$json['file']['full_url']}";
            } else {
                throw new BusinessException('文件上传失败:' . $json['message']);
            }
        }

        $article->save();

        Flash::success('保存文章记录成功!');

        return redirect($request->session()->get('articleBack',admin_action('Web\ArticlesController@index')));
    }

    /**
     * 返回编辑文章表单
     *
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function edit(Request $request,int $id)
    {

        $request->session()->put('articleBack',back()->getTargetUrl());

        $article = Article::findOrFail($id);

        $article_categories = Article::get_article_categories();

        $article_tags = Article::get_tags();

        $selected_tags = explode(',', $article->tags);;

        return view('admin.web.articles.edit', compact('article', 'article_categories', 'article_tags', 'selected_tags'));
    }

    /**
     * 修改文章记录
     *
     * @param ArticleRequest $request
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     * @throws BusinessException
     */
    public function update(ArticleRequest $request, int $id)
    {

        $args = $request->all();

        if (isset($args['tags'])) {
            $args['tags'] = implode(',', $args['tags']);
        }

        $article = Article::findOrFail($id);

        if ($image = $request->file('image')) {
            $json = upload_file($image);    //上传文件
            if ($json['code'] == 10000) {
                $args['image'] = $json['file']['full_url'];
            } else {
                throw new BusinessException('文件上传失败:' . $json['message']);
            }
        } else {
            //处理移除图片,如果存在这个参数,说明用户移除了图片
            if ($image = $request->input('image')) {
                $arr['image'] = $image;
            }
        }

        $article->update($args);

        Flash::success('修改文章记录成功!');

        return redirect($request->session()->get('articleBack',admin_action('Web\ArticlesController@index')));
    }

    /**
     * 根据id删除文章记录
     *
     * @param int $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function destroy(Request $request,int $id)
    {
        $request->session()->put('articleBack',back()->getTargetUrl());

        $article = Article::findOrFail($id);

        $article->delete();

        Flash::success('删除文章记录成功!');

        return redirect($request->session()->get('articleBack',admin_action('Web\ArticlesController@index')));
    }

    /**
     * 创建文章标签
     *
     * @param Request $request
     * @return string
     * @throws BusinessException
     */
    public function create_tag(Request $request)
    {
        $tag = $request->input('tag');

        if (empty($tag))
            throw new BusinessException('文章标签为 null');

        //查找数据库中是否存在相同标签,如果存在,抛异常
        if (Code::where('code', $tag)->exists())
            throw new BusinessException('重复文章标签');

        $code = new Code(['code' => $tag, 'name' => $tag, 'type_id' => Article::ARTICLE_TAG]);

        $code->save();

        return 'success';
    }

    /**
     * 预览文章详情
     *
     * @param int $id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function show(int $id){
        $article = Article::findOrFail($id);
        //获取文章所属分类,根文章分类
        $article_category = ArticleCategory::findOrFail($article->article_category_id);

        switch($article_category->parent){
            case self::ARTICLE_TYPE_ABOUT:
                return redirect()->action('ArticleController@about',['id' => $id, 'preview' => 1]);
                break;
            case self::ARTICLE_TYPE_ARTICLE:
                return redirect()->action('ArticleController@article_information_info',['id' => $id, 'preview' => 1]);
                break;
            case self::ARTICLE_TYPE_NOTICE:
                return redirect()->action('ArticleController@notice_article_info',['$article_id' => $id, 'preview' => 1]);
                break;
            case self::ARTICLE_TYPE_HELP:
                return redirect()->action('ArticleController@help_article_info',['$article_id' => $id, 'preview' => 1]);
            default:
                abort(404);
                break;
        }

//        return view('admin.web.articles.show',compact('article'));
    }
}